#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <microhttpd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "lib.h"
Pvoid_t	ja = (PWord_t) NULL;
int get_param(void *cls, enum MHD_ValueKind kind, const char *key, const char *value)
{
	if (strcmp(key, "str") == 0)
		strncpy(cls, value, 1023);
	return MHD_YES;
}
static int ahc_echo(void *cls,
	 struct MHD_Connection *connection,
	 const char *url,
	 const char *method,
	 const char *version,
	 const char *upload_data,
	 size_t * upload_data_size,
	 void **ptr)
{
	static int	dummy;
	const char     *page = cls;
	char	*o;
	struct MHD_Response *response;
	int	ret;
	char str[1024] = {0};
	if (0 != strcmp(method, "GET"))
		return MHD_NO;
	if (&dummy != *ptr)
	{
		*ptr = &dummy;
		return MHD_YES;
	}
	*ptr = NULL;
	MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND, get_param, str);
	if (str)
	{
		o = gbk_split(str, 0);
	}
	response = MHD_create_response_from_data(strlen(o), (void *)o, MHD_YES, MHD_NO);
	MHD_add_response_header(response,MHD_HTTP_HEADER_CONTENT_ENCODING,"GBK");
	ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
	MHD_destroy_response(response);
	return ret;
}
int main(int argc, char **argv)
{
	daemon(1,1);
	load_dict();
	load_chinese_stop_word();
	struct MHD_Daemon *d;
	if (argc != 2)
	{
		printf("%s PORT \n", argv[0]);
		return 1;
	}
	d = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY,
			     atoi(argv[1]),
			     NULL,
			     NULL,
			     &ahc_echo,
			     NULL,
			     MHD_OPTION_END);
	if (d == NULL)
		return 1;
	while(1) sleep(1000);
	MHD_stop_daemon(d);
	return 0;
}
